package com.dayatang.android.Activity;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.dayatang.android.Activity.Application.MyApplication;
import com.dayatang.android.Task.BaseTask;
import com.dayatang.android.Util.MapUtility;
import com.dayatang.android.config.Config;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;

public abstract class MapBaseActivity extends MapActivity {

	private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;  //语音
	protected MyApplication myApplication;
	
	public MapView mapView = null;
	protected MapController mapController;
	public List<Overlay> overlays;

	public View popView;
	protected EditText searchEditText;
	protected List<GeoPoint> geoPoints = new ArrayList<GeoPoint>();
	
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		myApplication = (MyApplication) this.getApplication();
		setContentView(R.layout.map_activity);
		searchEditText = (EditText) findViewById(R.id.map_searchContent1);
		
		InitMapView();
	}
	
	private void InitMapView() {
		mapView = (MapView) findViewById(R.id.map);

		mapView.setStreetView(true);
		mapView.setBuiltInZoomControls(true);
		mapView.displayZoomControls(true);

		mapController = mapView.getController();
		overlays = mapView.getOverlays();
		
		AddMyLocationOverlay();
	}

	private void AddMyLocationOverlay() {
		MyLocationOverlay myLocationOverlay = new MyLocationOverlay(this, mapView);
		overlays.add(myLocationOverlay);
		myLocationOverlay.enableCompass();
		myLocationOverlay.enableMyLocation();
		//myLocationOverlay.onTap(p, mapView);
		InitBtn();
	}
	
	private void InitBtn() {
		Button searchBtn = (Button) findViewById(R.id.map_searchBtn1);
		searchBtn.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				if(getSearchEditText().equals("")) {
					searchEditText.setError(getString(R.string.map_area_notnull));
				} else {
					SearchByAddress(getSearchEditText());
				}
			}
		});
		InitVoiceBtn();
	}

	private void SearchByAddress(String address) {
		JSONObject jsonObject = null;
		try {
			jsonObject = MapUtility.getLocationInfo(this,address);
			JSONArray array = jsonObject.getJSONArray("results");
			if (array.length() > 0) {
				GeoPoint geoPoint = MapUtility.getGeoPoint(jsonObject);
				
				mapController.setZoom(13);
				mapController.animateTo(geoPoint);
			} else {
				ToastShow(getString(R.string.map_area_error));
			}
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}
	
	protected String getDataByUrl(String url) {
		try {
			String result = new BaseTask(this).execute(url).get();
	    	if (result.equals(Config.ERROR)) {
	    		ToastShow(getString(R.string.server_unknown_error));
	    	} else if (result.equals(Config.SERVERDIE)) {
	    		ToastShow(getString(R.string.server_go_wrong));
	    	} else if (result.equals(Config.NODATA)) {
	    		ToastShow(getString(R.string.reports_alert_nofind_data));
	    	} else {
	    		return result;
	    	}
		} catch (InterruptedException e) {
			e.printStackTrace();
			ToastShow(getString(R.string.software_error));
		} catch (ExecutionException e) {
			e.printStackTrace();
			ToastShow(getString(R.string.software_error));
		}
    	return null;
	}
	
	protected void ToastShow(String info) {
		Toast.makeText(this, info, Toast.LENGTH_LONG).show();
	}
	
	private void InitPopView(){
		popView = super.getLayoutInflater().inflate(R.layout.overlay_pop, null);
	    mapView.addView( popView,new MapView.LayoutParams(MapView.LayoutParams.WRAP_CONTENT, MapView.LayoutParams.WRAP_CONTENT,
	            null, MapView.LayoutParams.BOTTOM_CENTER));
	    popView.setVisibility(View.GONE);
	    InitData();
	}

	
	/**
	 * 子类初始化数据
	 */
	protected abstract void InitData();
	
	private String getSearchEditText() {
		return searchEditText.getText().toString();
	}
	
	protected String getServerAddress() {
		return myApplication.getServerAddress();
	}
	
	protected String getUsername() {
		return myApplication.getUser().getUsername();
	}
	
	protected boolean isRouteDisplayed() {
		return false;
	}
	
    private void InitVoiceBtn() {
    	ImageButton speakButton = (ImageButton) findViewById(R.id.map_speakButton);
    	PackageManager pm = getPackageManager();
		final List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), Config.ZERO);
		speakButton.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				if(activities.size() > 0) {
					startVoiceRecognitionActivity();
				} else {
					ToastShow(getString(R.string.project_voice_nofind_recognizer));
				}
			}
		});
		InitPopView();
    }
    
    private void startVoiceRecognitionActivity()
	{
		// 通过Intent传递语音识别的模式
		Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
		// 语言模式和自由形式的语音识别
		intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
		// 提示语音开始
		intent.putExtra(RecognizerIntent.EXTRA_PROMPT,getString(R.string.map_area_search));
		// 开始执行我们的Intent、语音识别
		startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
	}
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK){
			ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
			searchEditText.setText(matches.get(0));
			SearchByAddress(matches.get(0));
		}
    	super.onActivityResult(requestCode, resultCode, data);
    }
    
    private static final int SETTINGS = 0;
    
    public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, SETTINGS, 0,"出行方式");
		return super.onCreateOptionsMenu(menu);
    }
    
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case SETTINGS:
				startActivity(new Intent(this,MapSettings.class));
				break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			this.finish();
			overridePendingTransition(R.anim.translucent_enter, R.anim.translucent_exit);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}
